#coding=utf-8
'''
Created on 2017-04-20

@author: sandy
'''
import sys,platform
sys.path.append("../")

from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet import reactor
from pycommon import TBaseProtocol
from twisted.internet import reactor
import logging
import CenterBuild
import HallManager
import CenterParse


class TestFactory(ReconnectingClientFactory):
    def __init__(self):
        ReconnectingClientFactory.maxDelay = 5
    
    def buildProtocol(self, addr):
        logging.warn(u"game->center CONNECTED!!!")
        self.resetDelay()
        return instance
    
    def startedConnecting(self, connector):
        logging.warn(u"game->center connecting!!!")
    
    def clientConnectionLost(self, connector, reason):
        logging.warn(u"game->center DOWN!!!")
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
        
    def clientConnectionFailed(self, connector, reason):
        logging.warn(u"game->center FAIL!!!")
        ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)



class CenterSrv(TBaseProtocol.TBaseProtocol):
    def __init__(self):
        self.reConnectCount = 0
        TBaseProtocol.TBaseProtocol.__init__(self)

    def start(self,ip,port):
        reactor.connectTCP(ip,port,TestFactory())

    def stop(self):
        logging.warn(u"CenterSrv.stop()")
    
    def connectionMade(self):
        logging.warn(u"CenterSrv.connectionMade()")
        TBaseProtocol.TBaseProtocol.reset(self)
        self.sendPacket(CenterBuild.loginCenter(self.reConnectCount))
        self.reConnectCount = 1
        allhallinfo = HallManager.instance.getAllHallInfo()
        if len(allhallinfo) > 0:
            self.sendPacket(CenterBuild.hallInfo(allhallinfo))
        logging.debug(u"send data sucess")

    def connectionLost(self, reason):
        logging.debug(u"CenterSrv.connectionLost %s", reason)

    def packetReceived(self, cmd, pkt):
        try:
            CenterParse.parse(self,cmd,pkt)        
            pass
        except Exception:
            logging.exception(u"centerparse.parse() cmd=%d" % cmd)

instance = CenterSrv()
if __name__ == '__main__':
    instance = CenterSrv()
    instance.start('127.0.0.1',8400);
    reactor.run()